package com.simen.hellobytes.android;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;

/**
 * author: SimenHi
 * create time: 2020-04-24 15:05
 * description:
 */
public class AppUtil {

    /**
     * 获取当前应用icon的位图资源
     *
     * @param context
     * @return
     */
    public static Drawable loadApplicationIcon(Context context) {
        try {
            ApplicationInfo applicationInfo = context.getApplicationInfo();
            PackageManager packageManager = context.getPackageManager();
            if (packageManager != null && applicationInfo != null) {
                return applicationInfo.loadIcon(packageManager);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getAppName(Context context){
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo info = pm.getPackageInfo(context.getPackageName(), 0);
            if(info.applicationInfo.labelRes!=0){
                return context.getResources().getString(info.applicationInfo.labelRes);
            }else{
                CharSequence appName = info.applicationInfo.loadLabel(pm);
                if(appName.length()>0){
                    return appName.toString();
                }else if(info.applicationInfo.nonLocalizedLabel!=null
                        && info.applicationInfo.nonLocalizedLabel.length()>0){
                    return info.applicationInfo.nonLocalizedLabel.toString();
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
        }
        return "";
    }

    /**
     * Get version info by current context
     * @return
     */
    public static String getAppVersionName(Context context) {
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo info = pm.getPackageInfo(context.getPackageName(), 0);
            return info.versionName;
        } catch (Exception e) {
            return "";
        }
    }

    public static int getAppVersionCode(Context context) {
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo info = pm.getPackageInfo(context.getPackageName(), 0);
            return info.versionCode;
        } catch (Exception e) {
            return 0;
        }
    }

}
